<?php 
	session_start();
include_once '../pushing.php';

if ($pushTime == true) {
	if ($_SESSION['UserId'] != 3)
		header('Location: push.php');
}
	
	if(!isset($_SESSION['UserId']))
	{
		header('Location: login.php');
   		die();
	}
	
	require_once '../mysqlConnect.php'; //mysqli database connect

	
function getPatientInfobyID($id) //returns all fields from patient table
{
	$conn = GetConnection();
	$sql = "SELECT * FROM Patient WHERE ID ='$id'";
	$value = $conn->query($sql);
	$rs = $value->fetch_assoc();
	$conn->close();
	return $rs;	
}
function getUserAnswers($id) //returns all fields from diagnostic test associated with selected patient
{
	$conn = GetConnection();
	$sql = "SELECT * FROM UserAnswerTest WHERE PID ='$id' AND TestID IS NOT NULL ORDER BY -RecordDate";
	$value = $conn->query($sql);
	$conn->close();
	return $value;	
}
function getTestName($testId)
{
	$conn = GetConnection();
	$sql = "SELECT Name FROM Test WHERE ID = '$testId'";
	$value = $conn->query($sql);
	$rs = $value->fetch_assoc();
	$real = $rs['Name'];
	$conn->close();
	return $real;
}
function getPrescriptions($id)
{
	$conn = GetConnection();
	$sql = "SELECT P.StartDate, P.EndDate, P.Dosage, M.Name FROM Prescription P, Medication M WHERE PID = '$id' AND P.MedicationID = M.ID ORDER BY -StartDate";
	$value = $conn->query($sql);
	return $value;
	$conn->close();
}

function getAnswers($id, $sec) // returns question text, patient answer to question, and date recorded
{
	$conn = GetConnection();
$sql = "SELECT U.Answer, U.RecordDate, Q.Text FROM UserAnswer U, Question Q WHERE Q.ID = U.QuestionID AND U.PID = '$id' AND Q.SecID = '$sec' ORDER BY -U.RecordDate, Q.QNumber";
	//$sql = "SELECT U.Answer, U.RecordDate, Q.Text FROM Question Q LEFT OUTER JOIN UserAnswer U ON Q.ID = U.QuestionID WHERE U.PID = '1' AND Q.SecID = '2' ORDER BY - U.RecordDate, Q.QNumber";
	//i wasn't thinkin clearly: using left outer join only works once. The answer for a new question occurs once if it is true, and it is true at least once
	$value = $conn->query($sql);
	return $value;
	$conn->close();
}
function getNumQuestions($secID) // returns the number of questions from a section based on the passed section ID, 
//not including the date question
{
	$conn = GetConnection();
	$sql = "SELECT count(*) as Count FROM `Question` WHERE SecID = '$secID' AND Text != 'Date of Symptom Record'";
	$value = $conn->query($sql);
	$rs = $value->fetch_assoc();
	$returnValue = $rs['Count'];
	return $returnValue;
	$conn->close();
}

$patientInfo = getPatientInfobyID($_REQUEST['PatId']);
$answerInfo = getUserAnswers($_REQUEST['PatId']);
$prescriptionInfo = getPrescriptions($_REQUEST['PatId']);
$psychologicalInfo = getAnswers($_REQUEST['PatId'], 3);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print Patient</title>
<link rel="stylesheet" type="text/css" href="../Styler.css"/>
<link rel="stylesheet" type="text/css" href="../printStyler.css"/>

<style>
@PAGE landscape {size: landscape;}
TABLE {PAGE: landscape;}
</style> 
</head>
<body>

    <div id="title">
        <h1>Patient Information</h1>
        <h3>Patient: <?php echo $patientInfo['PatID'] . ' &nbsp; &nbsp; Date Diagnosed: ' . $patientInfo['DateDiagnosed']?></h3>
        
        <div id="alltablesLayout">
        
        
        	<!--  the table containing the basic information of the patient: DOB, gender, relationship status, etc -->
        	<!--  finished editing -->
            <div id="basicInfoTable">
             <table id="table1">
                
                <h4>Basic Information</h4>
                
                <tr>
                	<th>Date of Birth</th><td><?php echo $patientInfo['DOB']?></td>
                </tr>
                <tr>
                	<th>Gender</th><td><?php echo $patientInfo['Gender']?></td>
                </tr>
                <tr>
                	<th>Relationship Status</th><td><?php if($patientInfo['RelationshipStatus'] == 0) echo 'Single'; else echo 'In a Relationship';?></td>
                </tr>
                <tr>
                	<th>Occupation Status</th><td><?php if($patientInfo['OccupationStatus'] == 0) echo 'Unemployed'; else echo 'Employed';?></td>
                </tr>
                <?php if($patientInfo['OccupationStatus'] == 1) :?>
                <tr>
                	<th>Ticks in Work Environment</th><td><?php if($patientInfo['WorkHabitat'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                <?php endif?>
                <tr>
                	<th>Ticks in Hunting Environment</th><td><?php if($patientInfo['HuntHabitat'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                 <tr>
                	<th>Ticks in Play Environment</th><td><?php if($patientInfo['PlayHabitat'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                <tr>
                	<th>Ticks in Garden Environment</th><td><?php if($patientInfo['GardenHabitat'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                <tr>
                	<th>Tickbite Caused Original Disease</th><td><?php if($patientInfo['TickBite'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                <tr>
                	<th>Currently Has a Rash</th><td><?php if($patientInfo['Rash'] == 1) echo 'Yes'; else echo 'No';?></td>
                </tr>
                </table>
            </div>
            
            
            <!-- Diagnostic Test Information Table: tests patient has taken and the results -->
            <!--  finished editing -->
            <div id="testResultTable">
            <?php if($answerInfo->num_rows >= 1) { //if the results pulled from the database are not null?>
           		<table id="table2" border="1">
                    
                    <h4>Diagnostic Test Information</h4>
                   
                    <tr>
                        <th>Test Name</th><th>Result1</th><th>Result2</th><th>Date Taken</th>
                    </tr>
                    
                    <?php $DiagnosticTableColor = 1; // counter for background color change?>
                    <?php while($rs = $answerInfo->fetch_assoc()){ ?>
							<tr>
		                    	<td><?php echo getTestName($rs['TestID'])?></td><td><?php echo $rs['Answer1']?></td><td><?php echo $rs['Answer2']?></td><td><?php echo $rs['RecordDate']?></td>
		                    </tr>
						<?php 
						 
						$DiagnosticTableColor++; // increases background color counter
                    } ?>
                    
                </table>
                <?php } ?>
            </div>
            
            
            <!-- Table with prescription information: name of medication, daily sosage, startdate, enddate -->
            <!--  finished editing -->
            <div id="medicationTable">
	            <?php if($prescriptionInfo->num_rows >= 1) {?>
	            	<table id="table3" border="1">
	            	
	                    	<h4>Prescription Information</h4>
	                    
	                    <tr>
	                        <th>Name</th><th>Daily Dosage</th><th>Start Date</th><th>End Date</th>
	                    </tr>
	                    
	                    <?php $prescriptionTableColor = 1; ?>
	                    <?php while($presInfo = $prescriptionInfo->fetch_assoc()) { ?>
			                     <tr>
			                    	<td><?php echo $presInfo['Name']?></td><td><?php echo $presInfo['Dosage']?>mg</td><td><?php echo $presInfo['StartDate']?></td><td><?php echo $presInfo['EndDate']?></td>
			                    </tr>
		                    <?php 
	                                        
	                    	$prescriptionTableColor++; 
	                    } ?>
	                     
	                </table>
	           <?php } ?>
           </div>
                        
            
            <!-- table containing physical symptom information: arthritis/joint pain, fatigue, dizziness, etc -->
            <!--  finished editing -->
            <div id="physicalSymptomsTable">
            <?php  
            	$checkNullP = 0; // a check to see whether the question text does not equal the answer text. If the question text has reached the final row in
				// the query and the answer question text doesn't match the question text, the answer doesn't need to be updated
				
            	$chkNumAnswersPhysSymp = getAnswers($_REQUEST['PatId'], 2); // this is the results of any answers the patient has given to this test 
            	// down about 6 lines from here, the number of rows are checked using this variable, determining whether the patient has answers associated
            	// with the questions 
			
				
			if ($chkNumAnswersPhysSymp->num_rows >= 1) { // if the results from the original query are greater than one,
			 // in other words, if the patient has an associated physical symptoms filled out, if not, nothing should be displayed?>
			 
			 <?php 
			 	$physSympNumQuestions = getNumQuestions(2); // contains the number of questions in the physical symptoms section, not including the date question
				
				$physSympConn = GetConnection();
				
				$physSympTextQuery = "SELECT Text FROM Question Q WHERE SecID = '2' AND Text != 'Date of Symptom Record' ORDER BY QNumber";
				// retrieves all question text from section except the date text.
				$physSympText = $physSympConn->query($physSympTextQuery);?>
			 
			 
            	<table id="table4" border="1">
                	
                		<h4>Physical Symptom Information</h4>
                	
                	
                	<tr> 
                		<?php //column of titles?>
                		
						<?php for($i = 1; $i <= $physSympNumQuestions; $i++) {
							$physicalText = $physSympText->fetch_assoc(); // retrieves column title from table ?>
	                    	<th><?php echo $physicalText['Text']?></th>
                    	<?php } ?>
                    	
                    	<th>Record Date</th> <!--  prints record date last -->
                	</tr>
                	
                	<?php 
					$countPhysicalInfo = 2; // background color counter
					$physicalInfo = getAnswers($_REQUEST['PatId'], 2); // this is the results of any answers the patient has given to this test
					// query returns question UserAnswer.Answer, UserAnswer.RecordDate, and Question.Text
					?>
						
			        <?php 
			        // because user will not have filled out global symptom differences on the first time entering data
					// for a specific patient, $physicalInfo will always be less than $physSympNumQuestions			        
			        for($i = 1; $i <= ceil($physicalInfo->num_rows / $physSympNumQuestions); $i++) {
						
						//$physSympTextQuery = "SELECT Text FROM Question Q WHERE SecID = '2' ORDER BY QNumber LIMIT 0, $physSympNumQuestions";
						$physSympText = $physSympConn->query($physSympTextQuery); // need to retrieve the text again, 
						// as we used it already when we printed the row of questions?>
						<tr>		       	
						
				    	<?php 
							
							if ($checkNullP != 1) // explained above
					      		$physInfo = $physicalInfo->fetch_assoc(); // retrieve first row of answers
					      	else 
								$checkNullP = 0;
							
					       	$physicalText = $physSympText->fetch_assoc(); // we use this to match the questions
				        				// with the text. $physInfo has the question text, as does $physicalText
				        				// if they don't match up, it means that a question has not been answered
				        	$physSympDate = $physInfo['RecordDate']; // the date of 
				        
					       	//the loop to print out the answers
					       	//================================================================
					       	for ($t = 1; $t <= $physSympNumQuestions; $t++) {
				        	
				        		if ($physicalText['Text'] == $physInfo['Text']) { // question text and answer text are the same?>
					       				<td><?php if($physInfo['Answer'] == null) echo 'NA2'; else echo $physInfo['Answer'];?></td>
					       			<?php 
					       			if ($t != $physSympNumQuestions) { // if the row is not the last in the section
					       				// if the row is the last in the section, the query should not be updated, as it
					       				// will be updated twice, skipping a question
					       				$physInfo = $physicalInfo->fetch_assoc();
					       				$physicalText = $physSympText->fetch_assoc();
					       			}?>
					       		<?php }
					       		else { // the answer text and question text don't match ?>
					       				<td><?php echo 'NA';?></td>
					       			<?php 					       			
					       			if ($t != $physSympNumQuestions) { // if the row is not the last in the section
					       				$physicalText = $physSympText->fetch_assoc();
					       			}
					       			else if ($t == $neurPsySympNumQuestions)
					       				$checkNullP = 1;?>
					       			
					       		<?php } ?>
					       	<?php } ?>
					       	
					       	
					       	<?php //echo the date recorded
					       	//=============================================================?>         	
				           		<td><?php echo $physSympDate;?></td>
							<?php  
							
							$countPhysicalInfo++;
						?>
						</tr>
						<?php }?>
	                </table>
			<?php } ?>
		</div>
            
            
            <!-- neuropsychological symptoms table: attention impairment, anxiety/panic, etc -->
           	<div id="neuroPsychTable">
             
			<?php 
				$checkNull = 0; // a check to see whether the question text does not equal the answer text. If the question text has reached the final row in
				// the query and the answer question text doesn't match the question text, the answer doesn't need to be updated
			
                $chkNumAnswersNeuroPsySymp = getAnswers($_REQUEST['PatId'], 5);
			 
			 	 if ($chkNumAnswersNeuroPsySymp->num_rows >= 1) { ?>
			 	 
			 		<?php 
				 		$neurPsySympNumQuestions = getNumQuestions(5);
//echo $neurPsySympNumQuestions;
						$neuroPsySymConn = GetConnection();
						$neurPsyTextQuery = "SELECT Text FROM Question WHERE SecID = '5' AND Text != 'Date of Symptom Record' ORDER BY QNumber";
						$neuPsySympText = $neuroPsySymConn->query($neurPsyTextQuery);
					?>
			 	 														
            		<table id="table5" border="1">
	            	
                	
	                	<h4>Neuro-Psychological Symptom Information</h4>
                	
                	
                	<tr> <?php //column of titles?>
	                	
						<?php for($i = 1; $i <= $neurPsySympNumQuestions; $i++) {
							$neuroText =  $neuPsySympText->fetch_assoc();?>
                    		<th><?php echo $neuroText['Text']?></th>
                    	<?php } ?>
                    	
	                    <th>Record Date</th> <!--  prints record date last -->
                	</tr>
	                
                	<?php 
                		$countNeuroInfo = 2;
						$neuroPsychInfo = getAnswers($_REQUEST['PatId'], 5); 
					?>
	                
                	<?php for($i = 1; $i <= ceil($neuroPsychInfo->num_rows / $neurPsySympNumQuestions); $i++) {
	                	
					//	$neurPsyTextQuery = "SELECT Text FROM Question Q WHERE SecID = '5' ORDER BY QNumber LIMIT 0, $neurPsySympNumQuestions";
						$neuPsySympText = $neuroPsySymConn->query($neurPsyTextQuery);
						
						if ($checkNull != 1) // explained above
							$neuroPsyInfo = $neuroPsychInfo->fetch_assoc();
						else 
							$checkNull = 0;
							
						$neuroPsyText = $neuPsySympText->fetch_assoc();
						$neuroPsySympDate = $neuroPsyInfo['RecordDate'];
						?>
						<tr> 
				        <?php 
					       	//the loop to print out the answers
					       	//================================================================
					       	for ($t = 1; $t <= $neurPsySympNumQuestions; $t++) {
//echo $t."<br/>"; 
//echo $neuroPsyText['Text'] . ' :::: ' . $neuroPsyInfo['Text'] . "<br/>";
//echo $neuroPsyInfo['Answer'] ."<br/>";					       			
				        		if ($neuroPsyText['Text'] == $neuroPsyInfo['Text']) { // question text and answer text are the same?>
					       				<td><?php if($neuroPsyInfo['Answer'] == null) echo 'NA2'; else echo $neuroPsyInfo['Answer'];?></td>
					       			<?php  
					       			if ($t != $neurPsySympNumQuestions) { // if the row is not the last in the section
					       				// if the row is the last in the section, the query should not be updated, as it
					       				// will be updated twice, skipping a question
					       				$neuroPsyInfo = $neuroPsychInfo->fetch_assoc();
					       				$neuroPsyText = $neuPsySympText->fetch_assoc();
					       			}?>
					       		<?php }
					       		else { // the answer text and question text don't match ?>
					       				<td><?php echo 'NA';?></td>
					       			<?php 
					       			
					       			if ($t != $neurPsySympNumQuestions) { // if the row is not the last in the section, if it is, it is the last question
					       				// and updating it will simply return a null value
					       				$neuroPsyText = $neuPsySympText->fetch_assoc(); 
					       			}
					       			else if ($t == $neurPsySympNumQuestions)
					       				$checkNull = 1;
					       			?>
					       		<?php } ?>
					       	<?php } ?>
					       	
					       	
					       	<?php //echo the date recorded
					       	//=============================================================?>     	
				           		<td><?php echo $neuroPsySympDate;?></td>
							<?php  
							
							$countNeuroInfo++;
					?>		
					</tr>
				 <?php }?>
				  
               	 </table>
                <?php } ?>
            </div>
            
            
            <!-- psychological test information: results of anxiety, depression, cognition, global quality of life responses -->
            <!-- finished editing -->
            <div id="psychologicalTable">
            <?php if($psychologicalInfo->num_rows >= 1) {?>
            	<table id="table6" border="1">
                
                <h4>Psychological Test Information</h4>
                
                <tr>
                	<th>Record Date</th><th>Anxiety</th><th>Depression</th><th>Cognition</th><th>Global Health Quality of Life</th>
                </tr>
                 <?php $countPsychInfo = 1; ?>
                <?php for($i = 1; $i <= $psychologicalInfo->num_rows / 4; $i++) { ?>
					<tr>
				<?php if($i == 1) $psyInfo = $psychologicalInfo->fetch_assoc(); ?>
					<td><?php echo $psyInfo['RecordDate']?></td>
				<?php for ($y = 1; $y <= 4; $y++) {?>
                	  <td><?php echo $psyInfo['Answer']?></td>
                <?php $psyInfo = $psychologicalInfo->fetch_assoc(); 
				} ?>
                </tr>
				<?php $countPsychInfo++;}?>
                </table>
                <?php } ?>
            </div>
            
            
        </div>
   	</div>         
</body>
</html>